var redis = require('redis');
const util = require('util');
var client = redis.createClient(6379, '192.168.21.176', {
  password: '123456'
});
// var client = redis.createClient(6379, 'localhost');
var ms = require('ms');

const timespan = function (time) {
  var milliseconds = ms(time);
  return Math.floor(milliseconds / 1000);
};

const sleep = function (timeout){
  return new Promise(function (resolve){
    setTimeout(() => {
      resolve();
    }, timeout);
  });
};

client.on('connect', async function () {
  console.log('conncect');
  // client.set('hello', 'This is a value from jw fa');
  // client.get('hello', function (err, data) {
  //   console.log(data);
  // });
  // const get = function (key) {
  //   return new Promise(function (resolve, reject) {
  //     client.get(key, function (err, data) {
  //       if (err) {
  //         reject(err);
  //       } else {
  //         resolve(data);
  //       }
  //     });
  //   });
  // };
  // const promisify = function (func, scope) {
  //   return function (...args) {
  //     return new Promise(function (resolve, reject) {
  //       args.push(function (err, data) {
  //         if (err) {
  //           reject(err);
  //         } else {
  //           resolve(data);
  //         }
  //       });
  //       func.apply(scope, args);
  //     });
  //   };
  // };
  // const get = promisify(client.get, client);
  // const set = promisify(client.set, client);

  const get = util.promisify(client.get).bind(client);
  const set = util.promisify(client.set).bind(client);

  console.log(ms('2式s'));

  set('hello', 'jw');
  client.expire('hello', timespan('20s'));
  console.log(await get('hello'));

  await sleep(3000);
  console.log(await get('hello'));

  await set('arr', JSON.stringify([1, 2, 3])); // 数组需要转成字符串存储
  console.log(await get('arr'));
});
